package test;

/*public class ThreadLocalExample {
    public static ThreadLocal<Integer> threadLocal = new ThreadLocal<Integer>() {
        @Override
        protected Integer initialValue() {
            return 0;
        }
    };
    public static void main(String[] args) throws InterruptedException {
        threadLocal.set(1);
        System.out.println("main thread: " + threadLocal.get()); // 输出1

        // 创建一个新线程，并在其中获取ThreadLocal变量的值
        Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println("new thread: " + threadLocal.get()); // 输出0
            }
        });
        thread.start();
        thread.join();
    }
}*/
public class ThreadLocalExample {
    public static ThreadLocal<Integer> threadLocal = new InheritableThreadLocal<Integer>() {
        @Override
        protected Integer initialValue() {
            return 0;
        }
    };
    public static void main(String[] args) throws InterruptedException {
        threadLocal.set(1);
        System.out.println("main thread: " + threadLocal.get()); // 输出1

        // 创建一个新线程，并在其中获取ThreadLocal变量的值
        Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println("new thread: " + threadLocal.get()); // 输出1
            }
        });
        thread.start();
        thread.join();
    }
}

